package com.tensquare.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SmsUtil {
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    // 设置鉴权参数，初始化客户端
    private IAcsClient getClient() {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",// 地域ID
                accessKeyId,// 您的AccessKey ID
                accessKeySecret);// 您的AccessKey Secret
        return new DefaultAcsClient(profile);
    }

    public void sendSms(String mobile, String checkCode,
                        String signName, String templateCode) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //组装请求对象
//        request.putQueryParameter("RegionId", "cn-hangzhou");
        // 接收短信的手机号码
        request.putQueryParameter("PhoneNumbers", mobile);
        // 短信签名名称。
        // 请在控制台签名管理页面签名名称一列查看（必须是已添加、并通过审核的短信签名）。
        request.putQueryParameter("SignName", signName);
        // 短信模板ID
        request.putQueryParameter("TemplateCode", templateCode);
        // 短信模板变量对应的实际值，JSON格式。
        request.putQueryParameter("TemplateParam",
                "{\"code\":\"" + checkCode + "\"}");
        try {
            CommonResponse response = getClient().getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
